import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:lunar/lunar.dart';
import 'package:todo_app/components/Calendar/CalendarDayWidget.dart';
import 'package:todo_app/components/Calendar/CalendarSliverDelegate.dart';
import 'package:todo_app/components/Calendar/CalendarWeekday.dart';
import 'package:todo_app/components/FontIcon.dart';
import 'package:todo_app/constants/DColor.dart';
import 'package:todo_app/controllers/TodoController.dart';
import 'package:todo_app/controllers/definitions/TodoModel.dart';
import 'package:todo_app/hooks/CalendarController.dart';
import 'package:todo_app/layout/Gaps.dart';
import 'package:todo_app/pages/todo/components/TodoWidget.dart';
import 'package:todo_app/utils/AppNavigator.dart';
import 'package:todo_app/utils/ExtHelper.dart';

const List<String> weekList = ['一', '二', '三', '四', '五', '六', '日'];

class HomePage extends HookWidget {
  const HomePage({Key? key}) : super(key: key);

  final Duration halfYear = const Duration(days: 180);
  
  @override
  Widget build(BuildContext context) {
    useAutomaticKeepAlive();
    var now = useState(DateTime.now());
    var calendarController = useCalendarController();
    var pageTime = useState(DateTime.now());
    var todos = useState<List<TodoModel>>([]);
    var pageTodos = useState<List<TodoModel>>([]);
    var lunar = Lunar.fromDate(pageTime.value);
    
    // 获取当天的待办事项或者下一次待办事项
    useEffect(() {
      TodoController.listUsingGet(1, 10000).then((res) {
        todos.value = res.data?.records ?? [];
      });
      return () {};
    }, []);

    // 计算当前页面需要展示的提醒信息
    useEffect(() {
      pageTodos.value = todos.value.where((todo) {
        return (todo.alertTime > pageTime.value) == true && (todo.alertTime < pageTime.value.add(halfYear)) == true;
      }).toList();
      return () {

      };
    }, [pageTime.value, todos.value]);

    return CustomScrollView(
      slivers: [
        SliverAppBar(
          backgroundColor: DColor.primary,
          titleTextStyle: const TextStyle(color: Colors.white),
          title: Text(pageTime.value.toYM(), style: TextStyle(fontSize: 18.dp),),
          pinned: true,
          elevation: 0,
          actions: [
            GestureDetector(
              onTap: () {
                AppNavigator.pushNamed('publishTodo');
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 15.dp),
                child: const FontIcon(icon: FontIcons.folderPlus)
              ),
            )
          ]
        ),
        SliverPersistentHeader(
          delegate: CalendarSliverDelegate(
            bgColor: DColor.primary,
            startTime: DateTime(2020, 1, 1),
            endTime: DateTime(2100, 1, 1),
            currentPageTime: pageTime.value,
            calendarController: calendarController,
            weekdayHeader: CalendarWeekday(
              7, 
              44.dp,
              builder: (int weekday) {
                return Text(
                  weekList[weekday-1],
                  style: TextStyle(
                    fontSize: 12.dp,
                    color: Colors.white
                  ),
                );
              }
            ),
            dayWidgetBuilder:(DateTime date, bool isLastMonthDay, bool isNextMonthDay) {
              return CalendarDayWidget(
                onTap: (date) {
                  calendarController.goToDate(dateTime: date);
                  pageTime.value = DateTime.fromMillisecondsSinceEpoch(date.millisecondsSinceEpoch);
                },
                date: date,
                hasValue: pageTodos.value.valueInDay(date),
                selected: pageTime.value.isSameDay(date),
                isLastMonthDay: isLastMonthDay,
                isNextMonthDay: isNextMonthDay,
                current: now.value,
              );
            },
            currentPageDate: (DateTime date) {
              pageTime.value = DateTime.fromMillisecondsSinceEpoch(date.millisecondsSinceEpoch);
            },
          ),
          pinned: true,
        ),
        SliverToBoxAdapter(
          child: Container(
            padding: EdgeInsets.symmetric(
              horizontal: 15.dp,
              vertical: 12.dp
            ),
            child: Text.rich(
              TextSpan(
                style: TextStyle(
                  fontSize: 14.dp
                ),
                children: [
                  TextSpan(
                    text: pageTime.value.toYMD(),
                    style: TextStyle(color: DColor.title, fontWeight: FontWeight.bold, fontSize: 18.dp)
                  ),
                  TextSpan(
                    text: " 农历${lunar.getYearInGanZhi()}年${lunar.getMonthInChinese()}月${lunar.getDayInChinese()}",
                    style: TextStyle(color: DColor.descText, fontSize: 12.dp)
                  )
                ]
              ),
            ),
          ),
        ),
        SliverList.list(
          children: pageTodos.value.map<Widget>((todo) => TodoWidget(todo: todo)).toList()
        ),
        const SliverFillRemaining()
      ],
    );
  }
}